package com.im.partchat.ui.fragment.contact;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.im.partchat.R;
import com.im.partchat.adapter.ContactAdapter;
import com.im.partchat.base.BaseFragment;
import com.im.partchat.bean.User;
import com.im.partchat.mvp.persenter.ContactPresenter;
import com.im.partchat.utils.Navigation;
import com.im.partchat.widget.LetterListViewV2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import butterknife.BindView;

/**
 * Created by hhz on 2017/7/1.
 */
public abstract class ContactFragment extends BaseFragment implements AdapterView.OnItemClickListener, LetterListViewV2.OnTouchingLetterChangedListener {
    @BindView(R.id.txl_listview)
    ListView txlListview;
    @BindView(R.id.letter_listview)
    LetterListViewV2 letterListView;
    @BindView(R.id.tv_pop)
    TextView tvPop;

    private TextView count;

    protected ContactPresenter presenter;
    protected List<User> memList = new ArrayList<>();
    protected ContactAdapter adapter = null;
    protected HashMap<String, Integer> alphaIndexer;
    protected List<String> sections = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.frament_contact;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        super.initView(view, savedInstanceState);
        LinearLayout member_count = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.member_count, null);
        count = (TextView) member_count.findViewById(R.id.tv_count);
        letterListView
                .setOnTouchingLetterChangedListener(this);
        letterListView.setPop(tvPop);
        txlListview.addFooterView(member_count);
        adapter = new ContactAdapter(memList, getActivity());
        txlListview.setAdapter(adapter);
        txlListview.setOnItemClickListener(this);
        alphaIndexer = new HashMap<>();
    }

    @Override
    public void onLoadDataSuccess(Object o, String flag) {
        if (o == null) {
            showEmpty();
        } else {
            List<User> data = (List<User>) o;
            memList.clear();
            memList.addAll(data);
            if (memList.size() > 0) {
                count.setVisibility(View.VISIBLE);
                count.setText(getResources().getString(R.string.member_count, memList.size()));
            } else {
                count.setVisibility(View.GONE);
            }
            adapter.notifyDataSetChanged();
            if (memList.isEmpty()) {
                showEmpty();
                letterListView.setVisibility(View.GONE);
            } else {
                showPageSuccess();
                letterListView.setVisibility(View.VISIBLE);
                sections.clear();
                initAlphaIndexer();
                letterListView.setAlphas(sections);
                letterListView.invalidate();
            }
        }
    }

    /**
     * 初始化拼音首字母和列表索引
     */
    protected void initAlphaIndexer() {
        if (!memList.isEmpty()) {
            for (int i = 0; i < memList.size(); i++) {
                // 当前汉语拼音首字母
                String currentStr = getAlpha(memList.get(i).getJp());
                // 上一个汉语拼音首字母，如果不存在为“ ”
                String previewStr = (i - 1) >= 0 ? getAlpha(memList.get(i - 1)
                        .getJp()) : " ";
                if (!previewStr.equals(currentStr)) {
                    String name = getAlpha(memList.get(i).getJp());
                    alphaIndexer.put(name, i);
                    sections.add(name);
                }
            }
        }
    }

    /**
     * 获取拼音简拼首字母
     *
     * @param str
     * @return
     */
    public static String getAlpha(String str) {
        if (str == null) {
            return "#";
        }
        if (str.trim().length() == 0) {
            return "#";
        }
        char c = str.trim().substring(0, 1).charAt(0);
        // 正则表达式，判断首字母是否是英文字母
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");
        if (pattern.matcher(c + "").matches()) {
            return (c + "").toUpperCase(Locale.getDefault());
        } else {
            return "#";
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long arg3) {
        if (memList == null || memList.isEmpty() || position >= memList.size()) {
            return;
        }
        Navigation.navigatePerson(memList.get(position).getId());
    }


    @Override
    public void onTouchingLetterChanged(String s) {
        if (alphaIndexer != null && alphaIndexer.get(s) != null) {
            int position = alphaIndexer.get(s) + txlListview.getHeaderViewsCount();
            txlListview.setSelection(position);
        }
    }
}
